<?php

declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class CitySettings extends Model
{
    public $timestamps = false;

    public $defaultValues = [
        'city_id'               => 0,
        'enabled'               => 0,
        'service_hour_start'    => 0.0,
        'service_hour_end'      => 0.0,
        'service_interval'      => 0.0,
        'service_weekdays'      => 0,
        'reservation_hour'      => 0.0,
        'phone_number'          => '',
        'show_phone'            => 0,
        'reservation_day_limit' => 0,
    ];
    protected $table = 'city_settings';

    protected $fillable = [
        'enabled', 'service_hour_start', 'service_hour_end', 'service_interval', 'service_weekdays', 'reservation_hour', 'phone_number', 'show_phone', 'reservation_day_limit',
    ];

    public function getDefaultSettings()
    {
        $data = static::where(['city_id' => 0])->first();

        return $data ? (array) $data->toArray() : [];
    }

    public function updDefaultSettings($updData)
    {
        $where = ['city_id' => 0];
//        $defaults = array_fill_keys($this->fillable, '');
//        $updData = array_merge($this->defaultValues, array_intersect_key($updData, $this->defaultValues));
        //print_r($updData);exit;
        $upd = static::where($where)->update($updData);

        return is_int($upd);
    }

    public function getSettings(int $cityId)
    {
        $data = static::where(['city_id' => $cityId])
            ->first();

        return $data ? (array) $data->toArray() : [];
    }

    public function getEnabledSettings(int $cityId)
    {
        $data = static::where(['city_id' => $cityId, 'enabled' => 1])
            ->first();

        return $data ? (array) $data->toArray() : [];
    }

    public function citySettingsExists(int $cityId)
    {
        $where = [
            'city_id' => $cityId,
        ];

        return static::where($where)->exists();
    }

    public function updCitySettings(int $cityId, array $updData)
    {
        $updData = array_intersect_key($updData, $this->defaultValues);
        if (isset($updData['city_id'])) {
            unset($updData['city_id']);
        }
        $upd = static::where(['city_id' => $cityId])->update($updData);

        return is_int($upd);
    }

    public function addCitySettings($data)
    {
        $data = array_merge($this->defaultValues, array_intersect_key($data, $this->defaultValues));

        return static::insert($data);
    }

    public function hour2float($hourStr)
    {
        [$hour, $minute] = explode(':', $hourStr);
        $hour            = intval($hour);
        if ($minute == '30' || $minute > 0) {
            $hour += 0.5;
        }

        return $hour;
    }
}
